<template>
    <view class="home-container" :class="{ 'mobile': isMobile }">
        <!-- 顶部导航栏 -->
        <view class="header fade-in">
    <view class="user-info" @click="goToProfile" style="transition: var(--transition);">
                <view class="avatar-wrapper" @click.stop="goToAvatarEditor">
                    <image :src="getAvatarUrl(userInfo.avatar)" class="avatar-canvas" />
                </view>
                <view class="text-info">
                    <text class="username">{{ userInfo.name || '访客' }}</text>
                    <view class="meta">
                        <text class="level">Lv.{{ userInfo.level || 1 }}</text>
                        <text v-if="userInfo.role === 'admin'" class="role-tag admin">
                            <text class="fa fa-user-shield"></text> 管理员
                        </text>
                    </view>
                </view>
            </view>
            <view class="user-actions">
                <button v-if="userInfo.role === 'admin'" @click="goToAdmin" class="action-btn admin-btn">
                    <text class="fa fa-cogs"></text>
                    <text v-if="!isMobile" class="btn-text">管理</text>
                </button>
                <button @click="handleLogout" class="action-btn logout-btn">
                    <text class="fa fa-sign-out-alt"></text>
                    <text v-if="!isMobile" class="btn-text">退出</text>
                </button>
            </view>
        </view>

        <!-- 欢迎卡片 -->
        <view class="welcome-card fade-in-delay-1">
            <view class="card-content">
                <text class="welcome-title">欢迎回来, {{ userInfo.name }}!</text>
                <text class="welcome-subtitle">今天也要元气满满哦 (づ｡◕‿‿◕｡)づ</text>
            </view>
            <view class="card-actions">
                <button class="card-btn" @click="goToSpace">
                    <i class="fa fa-rocket"></i> 我的空间
                </button>
            </view>
        </view>

        <!-- 公告栏 -->
        <view v-if="latestNotice" class="notice-bar fade-in-delay-2">
            <text class="fa fa-bullhorn notice-icon"></text>
            <view class="notice-content">
                <text class="notice-title">{{ latestNotice.title }}</text>
                <text class="notice-text">{{ latestNotice.content }}</text>
            </view>
        </view>

        <!-- 发布动态入口 -->
        <view v-if="recentPosts.length > 0" class="create-post-entry" @click="showPostModal">
            <view class="entry-avatar-wrapper">
                <image :src="getAvatarUrl(userInfo.avatar)" class="avatar-canvas-small" />
            </view>
            <view class="entry-input">
                <text class="entry-placeholder">分享你的新鲜事...</text>
            </view>
            <button class="entry-button" @tap.stop="showPostModal">
                <i class="fa fa-paper-plane"></i>
                <text>发布</text>
            </button>
        </view>
        <view v-else class="large-create-post-entry" @click="showPostModal">
            <view class="large-entry-content">
                <image :src="getAvatarUrl(userInfo.avatar)" class="large-avatar" />
                <view class="large-entry-text">
                    <text class="large-placeholder">分享你的第一条动态吧~</text>
                </view>
            </view>
            <button class="large-entry-button">
                <i class="fa fa-paper-plane"></i>
                <text>发布动态</text>
            </button>
        </view>

        <!-- 主要内容区 -->
        <view class="main-content">
            <!-- 动态列表 -->
            <view class="posts-section">
                <view class="section-header">
                    <text class="section-title">最新动态</text>
                    <text class="section-subtitle">发现有趣的灵魂</text>
                </view>
                <view class="posts-list">
    <!-- 动态为空时显示大尺寸发布入口 -->
    <view v-if="recentPosts.length === 0" class="empty-state-placeholder"></view>
    <view v-else v-for="post in recentPosts" :key="post.id" class="post-card">
                        <view class="post-header">
                            <view class="post-author">
                                <image :src="getAvatarUrl(post.userAvatar)" class="post-avatar" />
                                <view class="author-info">
                                    <text class="author-name">{{ post.userName }}</text>
                                    <text class="post-time">
发布时间: {{ formatTime(post.created_at) }}
  </text>
                                </view>
                            </view>
                        </view>
                        <view class="post-content">{{ post.content }}</view>
                        <view class="post-actions">
                            <button class="post-action" :class="{ 'liked': post.isLiked }" @tap="likePost(post.id)">
                                <text class="fa" :class="post.isLiked ? 'fas fa-heart' : 'far fa-heart'"></text>
                                <text>{{ post.likes || 0 }}</text>
                            </button>
                            <button class="post-action" @tap="showCommentInput(post.id)">
                                <text class="far fa-comment"></text>
                                <text>{{ post.comments?.length || 0 }}</text>
                            </button>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 发布动态弹窗 -->
        <uni-popup ref="postModal" type="center">
            <view class="post-modal">
                <view class="modal-header">
                    <text class="modal-title">分享新动态</text>
                    <button class="close-btn" @tap="hidePostModal">
                        <text class="fa fa-times"></text>
                    </button>
                </view>
                <textarea 
                    v-model="newPost.content"
                    class="post-textarea"
                    placeholder="今天想分享些什么呢..."
                    maxlength="500"
                ></textarea>
                <view class="modal-footer">
                    <text class="char-count">{{ newPost.content.length }}/500</text>
                    <view class="modal-actions">
                        <button class="modal-btn cancel" @tap="hidePostModal">取消</button>
                        <button class="modal-btn submit" 
                                @tap="submitPost" 
                                :disabled="isSubmitting || !newPost.content.trim()">
                            {{ isSubmitting ? '发布中...' : '发布' }}
                        </button>
                    </view>
                </view>
            </view>
        </uni-popup>

        <!-- 一键回顶按钮 -->
        <view v-if="showBackToTop" class="back-to-top" @click="backToTop">
            <text class="fa fa-arrow-up"></text>
        </view>

        <!-- 页脚 -->
        <view class="footer">
            <text class="copyright">萌友次元 &copy; 2024 | 用创意连接每个次元</text>
        </view>
    </view>
</template>

<script>
import { createPost, getRecentPosts, likePost } from '@/api/post'
import { getUserInfo } from '@/api/user'
import { getLatestNotice } from '@/api/notice'
import { generateAvatarSvg } from '@/utils/avatar'
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import { useUserStore } from '@/stores/user'
import { formatTime } from '../../utils/date-utils';


export default {
    components: {
        UniPopup
    },
    data() {
        return {
            userInfo: {
                name: '',
                level: 1,
                role: 'user',
                avatar: null
            },
            recentPosts: [],
            newPost: {
                content: ''
            },
            notice: '',
            isSubmitting: false,
            ctx: null,
            isLoading: false,
            checkLoginRetries: 0,
            isMobile: false,
            entryCtx: null,
            latestNotice: null,
            showBackToTop: false
        }
    },
    onLoad() {
        console.log('Home page onLoad')
        this.isMobile = uni.getSystemInfoSync().windowWidth < 768;
        this.initializeHome()
    },
    onShow() {
        console.log('Home page onShow')
        if (this.userInfo.name) {
            this.fetchRecentPosts()
        }
    },
    onPageScroll(e) {
        this.showBackToTop = e.scrollTop > 200;
    },
    methods: {
            showPostModal() {
            this.$refs.postModal.open();
        },
        hidePostModal() {
            this.$refs.postModal.close();
        },
        getAvatarUrl(config) {
            return generateAvatarSvg(config);
        },
        async initializeHome() {
            try {
                const isLoggedIn = await this.checkLoginStatus()
                if (isLoggedIn) {
                    await Promise.all([
                        this.fetchUserInfo(),
                        this.fetchRecentPosts(),
                        this.fetchLatestNotice()
                    ])
                }
            } catch (error) {
                console.error('Home initialization failed:', error)
            }
        },
        
        async checkLoginStatus() {
            const userStore = useUserStore();
            const userId = userStore.userId;
            const token = userStore.token;
            
            if (!userId || !token) {
                console.log('未找到登录信息，跳转到登录页');
                uni.reLaunch({
                    url: '/pages/login/login'
                })
                return false;
            }
            
            console.log('已找到登录信息, userId:', userId);
            return true;
        },
        
        async fetchUserInfo() {
            try {
                const userStore = useUserStore();
                this.userInfo = {
                    name: userStore.userName,
                     level: userStore.level || 1,
                     role: userStore.role || 'user',
                     avatar: userStore.avatar
                };
                console.log('Loaded user info from store:', this.userInfo)
                // Draw avatars after getting user info
                this.$nextTick(() => {
                    if (this.userInfo.avatar) {
                        // 可以在这里添加头像渲染逻辑
                    }
                })
            } catch (error) {
                console.error('获取用户信息失败:', error)
                // 如果获取失败，可能是token失效，引导用户重新登录
                uni.showToast({
                    title: '用户信息获取失败，请重试',
                    icon: 'none'
                })
                const userStore = useUserStore();
                userStore.logout();
                uni.reLaunch({ url: '/pages/login/login' });
            }
        },

        // 获取最近动态
        async fetchRecentPosts() {
            try {
                const posts = await getRecentPosts(10) // 获取最近10条动态
                if (Array.isArray(posts)) {
                    // 双重保险：即使后端返回顺序有误，前端再次排序
                    posts.sort((a, b) => new Date(b.createdAt || b.CreatedAt) - new Date(a.createdAt || a.CreatedAt));
                    
                    this.recentPosts = posts.map(post => ({
                        ...post,
                        isLiked: false, // TODO: 后端需要提供是否已点赞的信息
                        userName: post.user ? post.user.name : '未知用户',
                        userAvatar: post.user ? post.user.avatar : null
                    }));

                    // 绘制所有动态的头像
                    this.$nextTick(() => {
                    });
                } else {
                    this.recentPosts = [];
                }
            } catch (error) {
                console.error('获取最近动态失败:', error)
                uni.showToast({
                    title: '获取动态失败',
                    icon: 'none'
                })
            }
        },

        // 下拉刷新
        onPullDownRefresh() {
            console.log('触发下拉刷新');
            this.handleRefresh();
        },

        // 下拉刷新处理
        async handleRefresh() {
            try {
                // 并行获取用户信息和最新动态，提高刷新速度
                await Promise.all([this.fetchUserInfo(), this.fetchRecentPosts()]);
                uni.showToast({
                    title: '刷新成功',
                    icon: 'success'
                });
            } catch (error) {
                console.error('刷新失败:', error);
                uni.showToast({
                    title: '刷新失败，请稍后再试',
                    icon: 'error'
                });
            } finally {
                // 无论成功或失败，都停止下拉刷新动画
                uni.stopPullDownRefresh();
            }
        },

        // 关闭公告
        closeNotice() {
            this.notice = ''
        },

        // 提交动态
        async submitPost() {
            if (!this.newPost.content.trim()) {
                uni.showToast({
                    title: '内容不能为空',
                    icon: 'none'
                });
                return;
            }
            this.isSubmitting = true;
            try {
                await createPost({
                    content: this.newPost.content,
                    user_id: this.userInfo.id
                });
                this.hidePostModal();
                uni.showToast({
                    title: '发布成功！',
                    icon: 'success'
                });
                await this.fetchRecentPosts();
            } catch (error) {
                console.error("发布动态失败:", error);
                uni.showToast({
                    title: '发布失败',
                    icon: 'error'
                });
            } finally {
                this.isSubmitting = false;
            }
        },

        // 格式化时间
        formatTime(dateString) {
            console.log('formatTime input:', dateString);
            if (!dateString) return '未知时间';
            
            // 处理ISO 8601带时区格式
            let adjustedDateString = dateString;
            
            // 修复毫秒部分 (确保三位数)
            adjustedDateString = adjustedDateString.replace(/(\.\d{1,2})(?=[+-])/, (match) => {
                console.log('Fixing milliseconds:', match);
                return match.padEnd(4, '0'); // .64 → .640, .6 → .600
            });
            
            // 修复时区格式 (例如将+08:00转换为+0800)
            adjustedDateString = adjustedDateString.replace(/([+-]\d{2}):(\d{2})$/, '$1$2');
            console.log('Adjusted date string:', adjustedDateString);
            
            // 尝试多种解析方式
            let date = new Date(adjustedDateString);
            if (isNaN(date.getTime())) {
                console.log('First parse failed, trying with T replaced');
                date = new Date(adjustedDateString.replace('T', ' '));
            }
            if (isNaN(date.getTime())) {
                console.log('Second parse failed, trying original string');
                date = new Date(dateString);
            }
            
            if (isNaN(date.getTime())) {
                console.error('Failed to parse date:', dateString);
                return `无效时间: ${dateString.substring(0, 16)}`;
            }
            
            const now = new Date();
            const diffMs = now - date;
            const diffSecs = Math.floor(diffMs / 1000);
            const diffMins = Math.floor(diffSecs / 60);
            const diffHours = Math.floor(diffMins / 60);
            const diffDays = Math.floor(diffHours / 24);
            
            console.log('Date parsed successfully:', date, 'Diff days:', diffDays);
            
            if (diffSecs < 60) return '刚刚';
            if (diffMins < 60) return `${diffMins}分钟前`;
            if (diffHours < 24) return `${diffHours}小时前`;
            if (diffDays < 30) return `${diffDays}天前`;
            
            // 格式化日期为 年/月/日 时:分
            const year = date.getFullYear();
            const month = ('0' + (date.getMonth() + 1)).slice(-2);
            const day = ('0' + date.getDate()).slice(-2);
            const hours = ('0' + date.getHours()).slice(-2);
            const minutes = ('0' + date.getMinutes()).slice(-2);
            
            const formatted = `${year}/${month}/${day} ${hours}:${minutes}`;
            console.log('Final formatted time:', formatted);
            return formatted;
        },

        // 点赞动态
        async likePost(postId) {
            if (!postId) return
            try {
                await likePost(postId)
                // 更新本地状态
                const post = this.recentPosts.find(p => p.id === postId)
                if (post) {
                    post.isLiked = !post.isLiked
                    post.likes = (post.likes || 0) + (post.isLiked ? 1 : -1)
                }
                uni.showToast({
                    title: post.isLiked ? '点赞成功' : '取消点赞',
                    icon: 'success'
                })
            } catch (error) {
                console.error('点赞失败:', error)
                uni.showToast({
                    title: error.message || '点赞失败',
                    icon: 'none'
                })
            }
        },

        // 显示评论输入框
        showCommentInput(postId) {
            uni.showToast({
                title: '评论功能开发中',
                icon: 'none'
            })
        },


        // 导航方法
        navigateToSquare() {
            uni.switchTab({
                url: '/pages/square/square'
            })
        },
        navigateToAdmin() {
            uni.navigateTo({
                url: '/pages/admin/admin'
            })
        },
        goToAvatarEditor() {
            uni.navigateTo({
                url: '/pages/avatar/avatar'
            });
        },
        goToSpace() {
            uni.navigateTo({
                url: '/pages/space/space'
            });
        },

        // 退出登录
        handleLogout() {
            uni.showModal({
                title: '提示',
                content: '确定要退出登录吗？',
                success: (res) => {
                    if (res.confirm) {
                        console.log('执行退出登录')
                        const userStore = useUserStore();
                        userStore.logout();
                        uni.reLaunch({
                            url: '/pages/login/login'
                        })
                    }
                }
            })
        },

        goToAdmin() {
            uni.navigateTo({
                url: '/pages/admin/admin'
            })
        },

        // 获取最新公告
        async fetchLatestNotice() {
            try {
                const res = await getLatestNotice();
                console.log('公告API返回数据:', res);
                // 检查是否有有效的公告数据
                if (res && res.title) {
                    this.latestNotice = res;
                } else {
                    // 没有标题时显示默认公告
                    this.latestNotice = {
                        title: '暂无公告',
                        content: '当前没有最新公告信息'
                    };
                }
            } catch (error) {
                console.error("获取最新公告失败:", error);
                // 显示错误提示
                uni.showToast({
                    title: '公告加载失败',
                    icon: 'error'
                });
                // 错误时显示默认公告
                this.latestNotice = {
                    title: '公告加载失败',
                    content: '请稍后重试或联系管理员'
                };
            }
        },

        // 回到顶部
        backToTop() {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300
            });
        }
    }
}
</script>

<style scoped src="./home.css"></style>
  <style scoped>
    .large-create-post-entry {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 30px;
        background-color: var(--card-bg-color);
        border-radius: 16px;
        margin-bottom: 20px;
        box-shadow: var(--card-shadow);
        text-align: center;
    }

    .large-entry-content {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
    }

    .large-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        margin-right: 15px;
        border: 2px solid var(--primary-color);
    }

    .large-entry-text {
        font-size: 18px;
        color: var(--text-color);
    }

    .large-placeholder {
        font-weight: 500;
        color: var(--text-secondary-color);
    }

    .large-entry-button {
        background-color: var(--primary-color);
        color: white;
        border: none;
        border-radius: 30px;
        padding: 12px 24px;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: var(--transition);
    }

    .large-entry-button:hover {
        background-color: var(--primary-dark-color);
        transform: translateY(-2px);
    }
  </style>